package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/authorInfo")
public class AuthorServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        String blogId = req.getParameter("blogId");
        resp.setContentType("text/json; charset=utf8");
        if (blogId == null || "".equals(blogId)){
            // 参数少了
            resp.getWriter().write("{ \"ok\": false; \"reason\": \"参数缺失\" }");
            return;
        }
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectOneBlog(Integer.parseInt(blogId));
        if (blog == null){
            resp.getWriter().write("{ \"ok\": false; \"reason\": \"查询的博客不存在\" }");
            return;
        }

        UserDao userDao = new UserDao();
        User author = userDao.selectById(blog.getUserId());
        if (author == null) {
            resp.getWriter().write("{ \"ok\": false; \"reason\": \"查询的作者不存在\" }");
            return;
        }
        // 把密码去掉
        author.setPassword("");
        String photoAndGit = userDao.findPhotoByName(author.getUserName());
        String photoName = photoAndGit.split(" ")[0];
        String github = photoAndGit.split(" ")[1];
        author.setPhoto(photoName);
        if (github == null || github.equals("null")){
            github = "";
        }
        author.setGithub(github);

        //得到文章数
        List<Blog> blogs = getBlogsByUser(author);
        author.setCount(blogs.size());

        String getBlog = req.getParameter("getBlog");
        if (getBlog != null && !"".equals(getBlog)){
            resp.getWriter().write(objectMapper.writeValueAsString(blogs));
        }else {
            resp.getWriter().write(objectMapper.writeValueAsString(author));
        }
    }

    // 获取文章数
    public List<Blog> getBlogsByUser(User user){
        BlogDao blogDao = new BlogDao();
        return blogDao.selectBlogsByUser(user.getUserId());
    }
}
